package cn.com.controler.Comment;

import cn.com.controler.Util.JDBCUtil;
import cn.com.entity.Comment;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDAO {

    //添加评论
    public int addComment(Comment comment){
          String str = "insert into comment values(null,?,?,?,?)";
          Object []arr = new Object[]{comment.getCommentUserId(),comment.getCommentArtId(),comment.getCommentContent(),comment.getCommentTime()};
          return CommentDAOTemplete.insertdata(str, arr);
    }
    //根据id删除
    public int deletebyid(Integer id){
        String str = "delete from comment where CommentId = ?";
        Object []arr = new Object[]{id};
        return CommentDAOTemplete.insertdata(str,arr);
    }
    //根据帖子id查询评论
    public List selectcommentbyartid(Integer id){
        String str = "select *from comment where CommentArtId = ?";
        Object[] arr = new Object[]{id};
        return CommentDAOTemplete.selectdata(str,arr);
    }
    //根据用户id查询评论
    public List selectcommentbyuserid(Integer id){
        String str = "select *from comment where CommentUserId = ?";
        Object[] arr = new Object[]{id};
        return CommentDAOTemplete.selectdata(str,arr);
    }
    //查询所有评论
    public List selectallcomment(){
        String str = "select *from comment";
        Object[] arr = new Object[]{};
        return CommentDAOTemplete.selectdata(str,arr);
    }
    //获得评论对象姓名
    public String getdxname(int commentArtId){
        //String str = "SELECT DISTINCT Username FROM user,article where article.ArticleUserId = user.UserId and ArticleUserId=?";
        String str = "select Username from user,(select article.ArticleUserId e from article,comment where article.ArticleId = comment.CommentArtId and CommentUserId = ?) a where user.UserId = a.e";
        //String str = "select Username from comment,user where comment.CommentUserId = user.UserId and CommentId = ?;";
        Connection coll = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<String> list = new ArrayList<>();
        String name = "";
        coll = JDBCUtil.getConnection();
        try {
            statement = coll.prepareStatement(str);
            statement.setInt(1,commentArtId);
            resultSet = statement.executeQuery();
            while(resultSet.next()){
                return resultSet.getString(1);

            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(coll,statement,resultSet);
        }
        return null;
    }
}
